//
//  SearchResultViewController.m
//  B2C
//
//  Created by xiaowu on 2017/7/26.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "SearchResultViewController.h"
#import "CommodityCell.h"
#import "GoodDetailViewController.h"
#import "CommodityModel.h"
#import "PageNationModel.h"

@interface SearchResultViewController ()<UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger pageNumber;
@end

@implementation SearchResultViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        _dataArr = [NSMutableArray array];
        _pageNumber = 1;
        _keyword = @"";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configureUI];
    [self loadData];
}

#pragma mark - Method
- (void)configureUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
    [self.tableView registerClass:[CommodityCell class] forCellReuseIdentifier:@"cell"];
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageNumber = 1;
        [weakSelf loadData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageNumber += 1;
        [weakSelf loadData];
    }];
}

- (void)reloadUI {
    NSString *title = @"";
    if (self.currentType == GoodsVCTypeForSearch) {
        title = [NSString stringWithFormat:@"%@(%ld个结果)",self.keyword, self.dataArr.count];
    } else if (self.currentType == GoodsVCTypeForRecommend) {
        title = @"热门推荐";
    } else if (self.currentType == GoodsVCTypeForNew) {
        title = @"新品上市";
    }
    self.navigationItem.title = title;
    self.tableView.mj_footer.hidden = (self.dataArr.count == 0);
    [self.tableView reloadData];
}

- (void)loadData {
    NSString *url = URL_Get_Goods_List;
    if (self.currentType == GoodsVCTypeForSearch) {
        url = URL_Get_Goods_List;
    } else if (self.currentType == GoodsVCTypeForRecommend) {
        url = URL_Get_Hot_GoodsList;
    } else if (self.currentType == GoodsVCTypeForNew) {
        url = URL_Get_New_GoodsList;
    }
    [self loadListData:url];
}

#pragma mark - Network
- (void)loadListData:(NSString *)url {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.keyword forKey:@"keyword"];
    [parameters safeSetObject:PageSize forKey:@"pageSize"];
    [parameters safeSetObject:@(self.pageNumber) forKey:@"pageNumber"];
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:url parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *pagenationDic = [responseDic safeJsonObjectForKey:@"pagenation"];
            PageNationModel *pageNationModel = [PageNationModel mj_objectWithKeyValues:pagenationDic];
            if (pageNationModel.pageNumber == 1) {
                [weakSelf.dataArr removeAllObjects];
                [weakSelf.tableView.mj_footer resetNoMoreData];
            }
            if (pageNationModel.pageNumber == pageNationModel.totalPage) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            NSArray *dataArr = [responseDic safeJsonObjectForKey:@"data"];
            for (NSDictionary *modelDic in dataArr) {
                CommodityModel *model = [CommodityModel mj_objectWithKeyValues:modelDic];
                [weakSelf.dataArr addObject:model];
            }
            [weakSelf reloadUI];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [CommodityCell getRowNumberWithItemArr:self.dataArr];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CommodityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    [cell setValueForCell:[CommodityCell getCellItemArr:self.dataArr withIndexPath:indexPath]];
    __weak typeof(self) weakSelf = self;
    cell.block = ^(NSInteger index) {
        CommodityModel *model = [weakSelf.dataArr safeObjectAtIndex:indexPath.row * 2 + index];
        
        GoodDetailViewController *goodVC = [[GoodDetailViewController alloc] init];
        goodVC.gid = model.gid;
        [weakSelf.navigationController pushViewController:goodVC animated:YES];
    };
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [CommodityCell getHeight];
}

#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"";
    if (self.currentType == GoodsVCTypeForSearch) {
        title = @"未搜索到结果";
    } else if (self.currentType == GoodsVCTypeForRecommend) {
        title = @"暂无商品信息";
    } else if (self.currentType == GoodsVCTypeForNew) {
        title = @"暂无商品信息";
    }
    return [[NSAttributedString alloc] initWithString:title
                                           attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                        NSForegroundColorAttributeName:[UIColor grayTextColor]}];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {

    [self loadData];
}

@end
